﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;

namespace MKAdminCore.ToolKit.FileHelper
{
    public class FileHelper
    {
        #region
        /// <summary>
        /// 下载指定网络路径图片
        /// </summary>
        /// <param name="downloadUrl">网络图片地址</param>
        /// <param name="fileName">保存文件名(包含文件后缀)</param>
        /// <returns></returns>
        public static void DownLoadImage(string downloadUrl, string fileName)
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(downloadUrl) as HttpWebRequest;
            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream responseStream = response.GetResponseStream();

            //创建本地文件写入流
            Stream stream = new FileStream(fileName, FileMode.Create);

            byte[] bArr = new byte[1024];
            int size = responseStream.Read(bArr, 0, (int)bArr.Length);
            while (size > 0)
            {
                stream.Write(bArr, 0, size);
                size = responseStream.Read(bArr, 0, (int)bArr.Length);
            }
            stream.Close();
            responseStream.Close();
        }
        #endregion

        /// <summary>
        /// 裁剪图片并保存
        /// </summary>
        public static string CripImageBySize(string filePath, string destFilePath, string catalog, string fileName)
        {
            return "";
            //CatalogElement catalogConfig = FileCatalogHelper.Catalog[key];

            //Image originalImage = Image.FromFile(filePath);
            //int originImgWidth = originalImage.Size.Width;
            //int originImgHeight = originalImage.Size.Height;

            //string catalogName = string.Format("/{0}/{1}", catalog, fileName);
            //Bitmap b = new Bitmap(originImgWidth, 450);
            //if (originImgHeight > 450)
            //{
            //    try
            //    {
            //        using (Graphics g = Graphics.FromImage(b))
            //        {
            //            //清空画布并以透明背景色填充
            //            g.Clear(Color.Transparent);
            //            //在指定位置并且按指定大小绘制原图片的指定部分
            //            g.DrawImage(originalImage, new Rectangle(0, 0, b.Width, b.Height), new Rectangle(0, 0, b.Width, b.Height), GraphicsUnit.Pixel);
            //            //Image displayImage = new Bitmap(b, originImgWidth, originImgHeight);
            //            Image displayImage = new Bitmap(b, b.Width, b.Height);
            //            //CommonUtil.GUID
            //            string extensionName = Path.GetExtension(filePath);
            //            fileName = Guid.NewGuid().ToString("N") + extensionName;

            //            string newFilePath = Path.Combine(catalogConfig.DestFile.AbsolutePath, catalog, fileName);
            //            displayImage.Save(newFilePath);
            //            catalogName = string.Format("/{0}/{1}", catalog, fileName);
            //            //Bitmap bit = new Bitmap(b, dto.maxWidth, dto.maxHeight);
            //        }
            //    }
            //    catch (Exception e)
            //    {
            //        //LogHelper.Error("裁剪图片失败:" + e.Message);
            //    }
            //    finally
            //    {
            //        originalImage.Dispose();
            //        b.Dispose();
            //    }
            //}

            //return catalogName;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="files">文件绝对路径集合</param>
        /// <param name="key">保存文件的目录</param>
        /// <param name="time">每帧的时间(毫秒)/ms</param>
        /// <param name="repeat">是否重复</param>
        public static string ImgConvertToGif(List<string> files, int time, bool repeat, string key, string catalog)
        {
            return "";
            //CatalogElement catalogConfig = FileCatalogHelper.Catalog[key];
            //string filePath = Path.Combine(catalogConfig.TempFile.AbsolutePath, catalog);
            //if (!Directory.Exists(filePath))
            //    Directory.CreateDirectory(filePath);

            //string fileName = Guid.NewGuid().ToString("N") + ".gif";
            //string giffile = Path.Combine(filePath, fileName);

            //AnimatedGifEncoder e = new AnimatedGifEncoder();
            //e.Start(giffile);

            ////每帧播放时间
            //e.SetDelay(time);

            ////-1：不重复，0：重复
            //e.SetRepeat(repeat ? 0 : -1);

            //for (int i = 0, count = files.Count; i < count; i++)
            //{
            //    //   Image.FromStream(
            //    try
            //    {
            //        e.AddFrame(NetImgUriToImage(files[i]));
            //    }
            //    catch (Exception ex)
            //    {
            //        continue;
            //    }
            //    //Image.FromFile(files[i]);
            //}

            //e.Finish();

            //return fileName;
        }
        public static Image NetImgUriToImage(string imgUrl)
        {
            WebRequest request = WebRequest.Create(imgUrl);
            WebResponse response = request.GetResponse();
            Stream s = response.GetResponseStream();
            byte[] data = new byte[1024];
            int length = 0;
            MemoryStream ms = new MemoryStream();
            while ((length = s.Read(data, 0, data.Length)) > 0)
            {
                ms.Write(data, 0, length);
            }
            ms.Seek(0, SeekOrigin.Begin);

            return Image.FromStream(ms);
        }
        public static void GetCatalogFileName(string qrcodePath, out string catalog, out string fileName)
        {
            if (string.IsNullOrEmpty(qrcodePath))
            {
                catalog = "";
                fileName = "";
            }

            string[] path = qrcodePath.Replace("\\", "/").Split('/');

            if (path.Length > 1)
            {
                catalog = path[path.Length - 2];
                fileName = path[path.Length - 1];
            }
            else
            {
                catalog = "";
                fileName = "";
            }

        }
    }
    public enum VisitCatalog
    {
        //临时目录
        TempCatalog = 1,
        //正式目录
        DestCatalog = 2
    }
}
